<?php

/**
 * 同步百大会员数据
 */
namespace App\Service\OrderService;
use App\Service\BaseService;
use Service\AppService\IdService;
use App\Model\BdUserModel\BdUserRealName;
use App\Model\BdUserModel\BdUserAddress;
use App\Model\BbcMemberCenterModel\BbcMember;
use App\Model\BbcMemberCenterModel\BbcUser;
use App\Model\BdUserModel\BdUser;
use App\Model\BbcMemberCenterModel\BbcArea;
use Hyperf\DbConnection\Db;
use App\Model\BbcMemberCenterModel\BbcUserAddress;
use App\Model\BbcMemberCenterModel\BbcUserTransactionRecord;
class SyncBdUserService extends BaseService
{
    /**
     * 同步百大会员功能
     */
    public function startSyncUser() 
    {
        //$this->syncBdUser();
        $this->syncBdUserAddress();
    }
    
    /**
     * 同步会员数据
     */
    public function syncBdUser()
    {
        $limit = 2000;
        $lastId = 0;
        $run_start_time = microtime(true);
        while ( true )
        {
            $list = BdUser::instance()
            ->where('uin','>',$lastId)       
            ->orderBy('uin','asc')
            ->limit($limit)
            ->get()
            ->toArray();
            
            if( empty($list) ) {
                break;
            }
            
            $endRow = end($list);
            $lastId = $endRow['uin'];
            
            $start_time = microtime(true);
            $listMap = array_column($list,null,'account');
            $user_ids = array_column($list,'uin');
            $userRealNameList = BdUserRealName::instance()->whereIn('uin',$user_ids)->where('isDeleted',0)->get()->toArray();
            $userRealNameListMap = array_column($userRealNameList,null,'uin');
            echo $lastId.PHP_EOL;
            
            //判断是否写入过
            $accountRows = array_column($list,'account');
            $userList = BbcUser::instance()->whereIn('account',$accountRows)->get()->toArray();
            foreach ($userList as $us) {
                unset($listMap[$us['account']]);
            }
            
            if( empty($listMap) ) {
                continue;
            }
            
            $insertBatchMember = [];
            $insertBatchUser = [];
            $BbcUserTransactionRecord = [];
            foreach ($listMap as $user)
            {
                $user_id = $user['uin'];
                $mid = IdService::instance()->getOtherID();
                $insertBatchMember[] = [
                    'id'                => $mid,
                    'cd'                => $user['createTime'],
                    'status'            => $user['freeze'] == 'N' ? 1 : 0,
                    'mobile'            => $user['account'],
                    'is_verified'       => !empty($userRealNameListMap[$user_id]) ? 1 : 0 ,
                    'true_name'         => !empty($userRealNameListMap[$user_id]) ? $userRealNameListMap[$user_id]['realName'] : '' ,
                    'idcard'            => !empty($userRealNameListMap[$user_id]) ? $userRealNameListMap[$user_id]['idCard'] : '' ,
                    'gender'            => $user['sex'] == 'M' ? 0 : 1,
                    'birthday'          => !empty($user['birthday']) ? date("Y-m-d H:i:s",strtotime($user['birthday'])) : '0000-00-00 00:00:00',
                    'bd_user_id'        => $user_id,
                    //'df'                => $user['freeze'] == 'N' ? 1 : 0
                ];
                
                $uid = IdService::instance()->getOtherID();
                $insertBatchUser[] = [
                    'id'                => $uid,
                    'bd_user_id'        => $user_id,
                    'mid'               => $mid,
                    'cid'               => '1802876679185559554',
                    'sid'               => 1,
                    'nickname'          => (string)$user['nickName'],
                    'mobile'            => $user['account'],
                    'account'           => $user['account'],
                    'password'          => $user['pwd'],
                    'pay_password'      => $user['payPassword'],
                    'last_login_time'   => $user['createTime'],
                    'last_login_ip'     => $user['rip'],
                    'is_verified'       => !empty($userRealNameListMap[$user_id]) ? 1 : 0,
                    'source'            => '2',
                    'status'            => $user['freeze'] == 'N' ? 1 : 0,
                    'remark'            => '',
                    'df'                => 0,
                    'cd'                => $user['createTime'],
                    'create_user_id'    => 0,
                    'level_id'          => 0,
                    'points'            => 0,
                    'amount'            => 0,
                    'growth_value'      => 0,
                    'avatar'            => $user['headImgUrl']
                ];
                
                $BbcUserTransactionRecord[] = [
                    'id'    => IdService::instance()->getOtherID(),
                    'uid'   => $uid
                ];
            }
            
            BbcMember::instance()->insert($insertBatchMember);
            BbcUser::instance()->insert($insertBatchUser);
            BbcUserTransactionRecord::instance()->insert($BbcUserTransactionRecord);
            echo "耗时：".bcsub((string)microtime(true),(string)$start_time,3) . "秒".PHP_EOL;
        }
        echo "总耗时：".bcsub((string)microtime(true),(string)$run_start_time,3) . "秒".PHP_EOL;
    }
    
    /**
     * 同步会员收货地址数据
     */
    public function syncBdUserAddress()
    {
        $limit = 1000;
        $lastId = 0;
        $run_start_time = microtime(true);
        while ( true )
        {
            $list = BdUserAddress::instance()
            ->select([
                Db::raw('if(receiveProvince in("北京","上海","天津","重庆"),CONCAT(receiveProvince,"市"),receiveProvince) as receiveProvince'),
                Db::raw('if(receiveProvince in("北京","上海","天津","重庆"),"市辖区",receiveCity) as receiveCity'),
                'receiveDistrict',
                'receiverName',
                'receiverAddress',
                'receiverPhone',
                'isdefault',
                'deleteFlag',
                'createTime',
                'uin',
                'aid'
            ])
            ->where('aid','>',$lastId)
            ->orderBy('aid','asc')
            ->limit($limit)
            ->get()
            ->toArray();
            
            if( empty($list) ) {
                break;
            }
            
            $endRow = end($list);
            $lastId = $endRow['aid'];
            $start_time = microtime(true);
            
            $receiveProvinces   = array_column($list,'receiveProvince');
            $receiveCitys       = array_column($list,'receiveCity');
            $receiveDistricts   = array_column($list,'receiveDistrict');
            
            //获取省
            $areaProvinceList = BbcArea::instance()->select(['id','name'])->where('deep',1)->whereIn('name',$receiveProvinces)->get()->toArray();
            $areaProvinceListMap = array_column($areaProvinceList,null,'name');
            //获取市
            $areaCityList = BbcArea::instance()->select(['id','name'])->where('deep',2)->whereIn('name',$receiveCitys)->get()->toArray();
            $areaCityListMap = array_column($areaCityList,null,'name');
            //获取县
            $areaDistinctList = BbcArea::instance()->select(['id','name'])->where('deep',3)->whereIn('name',$receiveDistricts)->get()->toArray();
            $areaDistinctListMap = array_column($areaDistinctList,null,'name');
            
            $insertBatchMember = [];
            foreach ($list as $user)
            {
                $insertBatchMember[] = [
                    'id'                => IdService::instance()->getOtherID(),
                    'uid'               => 0,
                    'bd_user_id'        => $user['uin'],
                    'receive_name'      => $user['receiverName'],
                    'receive_address'   => $user['receiverAddress'],
                    'receive_phone'     => $user['receiverPhone'],
                    'province'          => !empty($areaProvinceListMap[$user['receiveProvince']]) ? $areaProvinceListMap[$user['receiveProvince']]['id'] : 0,
                    'city'              => !empty($areaCityListMap[$user['receiveCity']]) ? $areaCityListMap[$user['receiveCity']]['id'] : 0,
                    'district'          => !empty($areaDistinctListMap[$user['receiveDistrict']]) ? $areaDistinctListMap[$user['receiveDistrict']]['id'] : 0,
                    'is_default'        => $user['isdefault'] == 'Y' ? 1 : 0 ,
                    'cd'                => $user['createTime'],
                    'df'                => $user['deleteFlag'] == 'N' ? 0 : 1,
                ];
            }
            
            BbcUserAddress::instance()->insert($insertBatchMember);
            echo "耗时：".bcsub((string)microtime(true),(string)$start_time,3) . "秒".PHP_EOL;
        }
        echo "总耗时：".bcsub((string)microtime(true),(string)$run_start_time,3) . "秒".PHP_EOL;
    }
}
